#!/usr/bin/env python

import os
import urllib
import json

from  datetime import datetime

from google.appengine.api import users
from google.appengine.ext import ndb
from google.appengine.ext import db

import jinja2
import webapp2

from user import User

from baseClasses import BaseRequestHandler
import application_config 

JINJA_ENVIRONMENT = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__), 'markup')),
    extensions=['jinja2.ext.autoescape'],
    autoescape=True)


####################################################################################################
# Page Handlers

class Index(BaseRequestHandler):
    def get(self):
        self.anonymousRedirect()
        template = JINJA_ENVIRONMENT.get_template('company/index.html')
        self.template_values["ACCOUNT_ID"] = self.session["ACCOUNT_ID"]
        self.response.write(template.render(self.template_values))

        #self.session[self.app_config['SESSION']['ID']] = 'bar'
        #self.response.set_cookie(self.app_config['COOKIES']["AUTHENTICATION"], 'YAHOO', max_age=360, path='/')

        # template = JINJA_ENVIRONMENT.get_template('company_index.html')
        # self.response.set_cookie('page', 'get_company_index', max_age=360, path='/')
        
        # #user_name = self.request.get('user_name', DEFAULT_GUESTBOOK_NAME)

        # # Ancestor Queries, as shown here, are strongly consistent
        # # with the High Replication Datastore. Queries that span
        # # entity groups are eventually consistent. If we omitted the
        # # ancestor from this query there would be a slight chance that
        # # Greeting that had just been written would not show up in a
        # # query.
        # user_query = User.query(
        #     ancestor=user_key()).order(-User.created_date)
        # user_list = user_query.fetch(10)
        # self.template_values["company_list"] = user_list
        
        # self.response.write(template.render(self.template_values))
        

class AddCompany(BaseRequestHandler):
    def get(self):
        self.anonymousRedirect()
        template = JINJA_ENVIRONMENT.get_template('company/add.html')
        self.template_values["input"] = {
            'company_name' : ""
        }
        self.response.write(template.render(self.template_values))
    
    def post(self):
        self.anonymousRedirect()

        # sanitize user input

        # validate user input
        company_name = self.request.get('input_company_name')

        #find user key
        account_id = self.session["ACCOUNT_ID"]
        query = User.query(User.user_name == account_id.lower())
        result = query.fetch()
        if len(result) <= 0:
            # if not exists, return false
            template = JINJA_ENVIRONMENT.get_template('company/add.html')
            self.template_values["input"] = {
                'company_name' : company_name
            }
            self.response.write(template.render(self.template_values))
            return
        else:
            # exists, get user key
            user_key = result[0].key
            company = Company()
            company.company_name = company_name
            company.creator = user_key
            company.put()
            template = JINJA_ENVIRONMENT.get_template('company/add.html')
            self.response.write(template.render(self.template_values))
            return
        
class EditCompany(BaseRequestHandler):
    def get(self, *args, **kwargs):
        if len(args) > 0:
            entity_key = ndb.Key(urlsafe=args[0])
            result = entity_key.get()
            self.template_values["user"] = result
            
            template = JINJA_ENVIRONMENT.get_template('user_company.html')
            self.response.set_cookie('page', 'get_company_edit', max_age=360, path='/')
            self.response.write(template.render(self.template_values))
        else:
            self.response.write('Record not found.')
        
    def post(self, *args, **kwargs):
        try:
            template = JINJA_ENVIRONMENT.get_template('user_company.html')
            self.response.set_cookie('page', 'post_company_add', max_age=360, path='/')
            
            entity_key = ndb.Key(urlsafe=self.request.get('company_key'))
            target_entity = entity_key.get()
            target_entity.email = self.request.get('input_email')
            target_entity.first_name = self.request.get('input_first_name')
            target_entity.last_name = self.request.get('input_last_name')
            if users.get_current_user():
                target_entity.modifier = users.get_current_user()
            target_entity.modified_date = datetime.utcnow()
            target_entity.put()
            self.redirect('/company/')
        except Exception, e:
            self.response.write("failed")
            self.response.write(e)
            
class DeleteCompany(BaseRequestHandler):
    def get(self, *args, **kwargs):
        if len(args) > 0:
            #fetch
            entity_key = ndb.Key(urlsafe=args[0])
            result = entity_key.get()
            self.template_values["user"] = result
            
            template = JINJA_ENVIRONMENT.get_template('user_delete.html')
            self.response.set_cookie('page', 'get_user_delete', max_age=360, path='/')
            self.response.write(template.render(self.template_values))
        else:
            self.response.write('Record not found.')
        
    def post(self, *args, **kwargs):
        try:
            template = JINJA_ENVIRONMENT.get_template('user_add.html')
            self.response.set_cookie('page', 'post_user_add', max_age=360, path='/')
            
            entity_key = ndb.Key(urlsafe=self.request.get('user_key'))
            entity_key.delete()
            self.redirect('/user/')
        except Exception, e:
            self.response.write("failed")
            self.response.write(e)
        
class Index2(webapp2.RequestHandler):
    def get(self, *args, **kwargs):
        self.response.write(args)
        self.response.write(kwargs)
        self.response.write('Project List!')



####################################################################################################
# Models

def company_key(user_type_name='application_user'):
    """Constructs a Datastore key for a User entity.

    We use user_type_name as the key.
    """
    return ndb.Key('user_type', user_type_name)


class Company(ndb.Model):
    company_name = ndb.TextProperty()
    creator = ndb.KeyProperty()
    created_date = ndb.DateTimeProperty(auto_now_add=True)
    modifier = ndb.KeyProperty()
    modified_date = ndb.DateTimeProperty(auto_now_add=False)
    
    

####################################################################################################
# Routing

"""ZX: 
    It is recommended that the routing urls have (?i) to make it case-insensitive.
    Routing urls should end with slash (/).
    If there's no slash, browser (eg Google Chrome) might treat it as a document 
    and perform search instead of routing it.
"""
app = webapp2.WSGIApplication([
    #(r'(?i)^/projects/(\w+)*$', ProjectsPageHandler),
    (r'(?i)^/company/$', Index),
    (r'(?i)^/company/add$', AddCompany),
    (r'(?i)^/company/edit/(.+)$', EditCompany),
    (r'(?i)^/company/delete/(.+)$', DeleteCompany)
], debug=True, config=application_config.webapp2_config)


